package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.service.IVoucherOrderService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1验证手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //2如果不符合，返回错误
            return Result.fail("手机号格式错误！");
        }

        //3符合，生成验证码
        String code = RandomUtil.randomNumbers(6);
        //4保存验证码到session
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY + phone, code, RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
//        5发送验证码
        log.info("发送验证码成功，验证码：{}", code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1验证手机号
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            //2如果不符合，返回错误
            return Result.fail("手机号格式错误！");
        }
        String code = (String) stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + loginForm.getPhone());
        System.out.println(code);
        if (!code.equals(loginForm.getCode()) || code == null) {
            return Result.fail("验证码不一致");
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("phone", loginForm.getPhone());
        List<User> users = userMapper.selectList(userQueryWrapper);


        if (users.size() > 1) {
            return Result.fail("存在多个该手机用户，请换个手机号登录");
        } else if (users.size() == 0) {
            User user = new User();
            user.setPhone(loginForm.getPhone());
            user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
            int insert = userMapper.insert(user);
            if (insert != 1) {
                return Result.fail("插入失败");
            }
            String token = UUID.randomUUID().toString(true);
            Map<String, Object> map = BeanUtil.beanToMap(user,new HashMap<>(),
                    CopyOptions.create().setIgnoreNullValue(true).
                            setFieldValueEditor(
                                    new BiFunction<String, Object, Object>() {
                                        @Override
                                        public Object apply(String s, Object o) {
                                            return   o.toString();
                                        }
                                    }
                            ));
            stringRedisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY+token,map);
            stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY+token,30,TimeUnit.MINUTES);
            log.info("登陆成功");
            return Result.ok(token);
        }

        String token = UUID.randomUUID().toString(true);
        Map<String, Object> map = BeanUtil.beanToMap(users.get(0),new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true).
                        setFieldValueEditor(
                                new BiFunction<String, Object, Object>() {
                                    @Override
                                    public Object apply(String s, Object o) {
                                      return   o.toString();
                                    }
                                }
                        ));
        stringRedisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY+token,map);
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY+token,30,TimeUnit.MINUTES);
        log.info("登陆成功");
        return Result.ok(token);
    }
}
